import React, { useRef, useEffect, useState } from 'react';
import hljs from '../views/tools/highlight/highlight';
import ClipboardJS from 'clipboard';

interface CodeBlockProps {
  language?: string;
  code?: string;
  showLineNumbers?: boolean;
}

const CodeBlock: React.FC<CodeBlockProps> = ({
  language = 'javascript',
  code = '',
}) => {
  const codeRef = useRef<HTMLElement>(null);
  const copyButtonRef = useRef<HTMLDivElement>(null);
  const [copied, setCopied] = useState(false);
  let clipboard: ClipboardJS | null = null;

  // 初始化代码高亮和剪贴板
  useEffect(() => {
    // 代码高亮
    if (codeRef.current) {
      hljs.highlightElement(codeRef.current);
    }

    // 初始化剪贴板
    if (copyButtonRef.current) {
      clipboard = new ClipboardJS(copyButtonRef.current, {
        text: () => code
      });

      clipboard.on('success', () => {
        setCopied(true);
        setTimeout(() => setCopied(false), 2000);
      });
    }

    // 清理函数
    return () => {
      if (clipboard) {
        clipboard.destroy();
        clipboard = null;
      }
    };
  }, [code]); // 依赖 code 变化时重新执行

  // 处理复制逻辑
  const copyCode = () => {
    if (copyButtonRef.current) {
      copyButtonRef.current.click();
    }
  };


  return (
    <div >
      <div style={{ display: 'flex', justifyContent: 'space-between', backgroundColor: '#1a1a1aff', padding: '5px 10px', color: '#fff' }}>
        <span>{language}</span>
        <div
          ref={copyButtonRef}
          title="复制代码"
          onClick={copyCode}
        >
          {!copied ? (
            <div style={{ cursor: 'pointer' }}>📋 复制</div>
          ) : (
            <div>✅ 完成</div>
          )}
        </div>
      </div>
      <div className="code-block-content">
        <pre>
          <code
            ref={codeRef}
            className={language}
          >
            {code}
          </code>
        </pre>
      </div>
    </div>
  );
};

export default CodeBlock;